package com.wt.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wt.admin.entity.WqunAccount;
import com.wt.admin.entity.WqunSysMenu;
import com.wt.admin.entity.rewentity.LoginUser;
import com.wt.admin.mapper.WqunAdminMapper;
import com.wt.admin.mapper.WqunSysMenuMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;


@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private WqunAdminMapper userMapper;
    @Autowired
    private WqunSysMenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {

        //查询用户信息
        QueryWrapper<WqunAccount> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",userName).or().eq("email",userName);
        WqunAccount user = userMapper.selectOne(queryWrapper);

        //如果没有查询到信息就抛出异常
        if(Objects.isNull(user)){
            throw new RuntimeException("用户名或密码不存在");
        }

        //TODO 查询用户权限信息
        List<String> list = menuMapper.selectPermsByUserId(user.getId());
//        List<String> list = new ArrayList<>(Arrays.asList("test","admin"));

        //把数据封装成UserDetails返回
        return new LoginUser(user,list);
    }
}
